package com.spring.study.bean.definition;

import com.spring.study.bean.factory.UserFactory;
import com.spring.study.bean.factory.UserFactoryImpl;
import com.spring.study.domain.User;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Iterator;
import java.util.ServiceLoader;

public class SpecialBeanInstantinationDemo {

    public static void main(String[] args) {
        ApplicationContext applicationContext = new
                ClassPathXmlApplicationContext("classpath:META-INF/special-bean-instantiation-context.xml");
        AutowireCapableBeanFactory beanFactory = applicationContext.getAutowireCapableBeanFactory();
        ServiceLoader<UserFactory> serviceLoader = beanFactory.getBean("userFactoryServiceLoader",ServiceLoader.class);
        deplayServiceLoader(serviceLoader);
        //        demoServiceLoader();
        UserFactory userFactory = beanFactory.createBean(UserFactoryImpl.class);
        System.out.println(userFactory.createUser());
    }


    public static void demoServiceLoader() {
        ServiceLoader<UserFactory> serviceLoader =
                ServiceLoader.load(UserFactory.class,Thread.currentThread().getContextClassLoader());
        deplayServiceLoader(serviceLoader);
    }

    public static void deplayServiceLoader(ServiceLoader<UserFactory> serviceLoader) {
        Iterator<UserFactory> iterable = serviceLoader.iterator();
        while (iterable.hasNext()){
            UserFactory userFactory = iterable.next();
            System.out.println(userFactory.createUser());
        }
    }
}
